package cn.ytr.crm.web.controller;

import cn.ytr.crm.domain.Employee;
import cn.ytr.crm.service.IEmployeeService;
import cn.ytr.crm.service.IPermissionService;
import cn.ytr.crm.util.JsonResult;
import cn.ytr.crm.util.UserContext;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 用了 shiro 后该控制器没用了
 */
//@Controller
public class LoginController {
	
	//@Autowired
	private IEmployeeService employeeService;
	//@Autowired
    private IPermissionService permissionService;

	/**
	 * 处理 异步请求过来的登录
	 */
	//@RequestMapping("/loginAjax")
	@ResponseBody
	public JsonResult loginAjax(String name, String password) {
		JsonResult result = new JsonResult();

		//匹配传进来的用户名和密码是否能在数据库匹配
		Employee employee = employeeService.checkByNameAndPassword(name, password);
		if (employee == null) {
			result.mark("用户名和密码不匹配");
		} else {
			//用户名和密码匹配就把它存到 session 里
			UserContext.setCurrentUser(employee);
			//顺便查询该用户的所有的权限，存起来，不用权限拦截器每次都去数据库查
            UserContext.setCurrentUserPermission(permissionService.selectByEmpId(employee.getId()));
		}
        System.out.println(result);
        System.out.println("name = "+name+"，password = " +password);
		return result;
	}

	/**
	 * ajax 处理 注销登录 return "redirect:/login.html";
	 */
	//@RequestMapping("/logout")
	@ResponseBody
	public JsonResult logout(HttpSession session) {
		JsonResult jsonResult = new JsonResult();
		try {
			//删除登陆者信息 session
			session.removeAttribute("EMP_IN_SESSION");
			//删除登陆者权限 session
			session.removeAttribute("EMP_PERMISSION_IN_SESSION");
		    return jsonResult;
		} catch (Exception e) {
		    jsonResult.mark("服务器提示：操作失败");
		    e.printStackTrace();
		    return jsonResult;
		}
	}

}
